#!/usr/bin/env node

const fs = require('fs')

function mergeInterface(into, from) {
  const key = (item) => item.inputs ? `${item.name}/${item.inputs.length}` : item.name;
  const existing = into.reduce((acc, item) => {
    acc[key(item)] = true;
    return acc;
  }, {});
  const extended = from.reduce((acc, item) => {
    if (!(key(item) in existing))
      acc.push(item)
    return acc;
  }, into.slice());
  return into.concat(from)
}

function mergeComptroller(abi) {
  abi.Comptroller = mergeInterface(abi.Unitroller, abi[`Comptroller`])
  return abi;
}

function format(abi) {
  return JSON.stringify(abi, null, 4).replace(/^( {4}".*?)$/mg, '\n$1')
}

function main(path) {
  const abi = JSON.parse(fs.readFileSync(path))
  fs.writeFileSync(path, format(mergeComptroller(abi)))
}

main('networks/mainnet-abi.json')
